package jd.monitor.attach.util;
import java.io.File;
import java.lang.annotation.Annotation;

import org.apache.commons.io.FileUtils;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.mapper.CannotResolveClassException;
import com.thoughtworks.xstream.mapper.MapperWrapper;

public class XmlSerializableUtil
{
//  private final static  Logger logger = LoggerFactory.getLogger(XmlSerializableUtil.class);
  
  public static String serializeXML(Object obj, boolean flag)
  {
    XStream xStream = new XStream();
    if (flag) {
      xStream.autodetectAnnotations(true);
    }
    return xStream.toXML(obj);
  }
  
  public static <T> T deSerializeXML(final Class<T> type, String xmlObj, boolean flag)
  {
	xmlObj = xmlObj.replaceAll("&&", "&amp;&amp;");
	xmlObj = xmlObj.replaceAll("<=", "&lt;=");
	xmlObj = xmlObj.replaceAll(">=", "&gt;=");	
    XStream xStream = new XStream(new DomDriver())
    {
      protected MapperWrapper wrapMapper(MapperWrapper next)
      {
        return new MapperWrapper(next)
        {
          public boolean shouldSerializeMember(Class definedIn, String fieldName)
          {
            try
            {
              return (definedIn != Object.class) || (realClass(fieldName) != null);
            }
            catch (CannotResolveClassException cnrce)
            {
            	cnrce.printStackTrace();
//              Logger.error(this.getClass().getName() + "  包含未知节点:" + cnrce.getMessage());
            }
            return false;
          }
        };
      }
    };
    for (Annotation at : type.getAnnotations()) {
      if ((at instanceof XStreamAlias))
      {
        XStreamAlias alias = (XStreamAlias)at;
        if ((alias.value() != null) && (!alias.value().trim().equals("")))
        {
          xStream.alias(alias.value(), type);
          break;
        }
      }
    }
    xStream.alias(type.getSimpleName(), type);
    if (flag) {
      xStream.autodetectAnnotations(true);
    }
    return (T) xStream.fromXML(xmlObj);
  }

  public static String getXmlConfig(String file){
	  try {
		  return FileUtils.readFileToString(new File(PathUtil.revisionFilePath(file)));
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null ;
  }
  
}
